package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MapperUtils {

    private static SqlSessionFactory factory;

    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();

    static {
        try {
            InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static<T> T getMapper(Class<T> cls){
        //获取sqlSession对象
        SqlSession sqlSession = factory.openSession();
        tl.set(sqlSession);

        T mapper = sqlSession.getMapper(cls);
        return mapper;
    }

    public static void close(){
        SqlSession sqlSession = tl.get();
        if (sqlSession!= null){
            sqlSession.close();

            tl.remove();
        }
    }
    public static void commit(){
        SqlSession sqlSession = tl.get();
        if (sqlSession!= null){
            sqlSession.commit();
        }
    }
    public static void rollback(){
        SqlSession sqlSession = tl.get();
        if (sqlSession!= null){
            sqlSession.rollback();
        }
    }
}
